package com.wwwarehouse.common.activity.media;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;

import com.wwwarehouse.common.BuildConfig;
import com.wwwarehouse.common.R;
import com.wwwarehouse.common.activity.base.BaseActivity;
import com.wwwarehouse.common.adapter.media.UploadAdapter;
import com.wwwarehouse.common.bean.upload.FileUploadBean;
import com.wwwarehouse.common.bean.media.UploadType;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.media.OnItemPlusListener;
import com.wwwarehouse.common.custom_widget.media.OnItemPreviewListener;
import com.wwwarehouse.common.custom_widget.media.OnItemUploadListener;
import com.wwwarehouse.common.custom_widget.popupwindow.EasyPopupWindow;
import com.wwwarehouse.common.custom_widget.time_pick.DateUtil;
import com.wwwarehouse.common.eventbus_event.UploadImageEvent;
import com.wwwarehouse.common.eventbus_event.UploadSuccessEvent;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.FileUtils;
import com.wwwarehouse.common.tools.PermissionUtils;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.common.tools.ThreadUtils;
import com.wwwarehouse.common.tools.ToastUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

import static com.wwwarehouse.common.activity.media.SelectImageActivity.KEY_SELECT_IMAGE_PATH;
import static com.wwwarehouse.common.adapter.media.UploadAdapter.UPLOAD_TYPE_IMAGE;
import static com.wwwarehouse.common.adapter.media.UploadAdapter.UPLOAD_TYPE_PLUS;

public class UploadConfirmActivity extends BaseActivity implements PermissionUtils.PermissionCallbacks, View.OnClickListener, EasyPopupWindow.ChildClickListener {
    private ImageView mTopReturn;
    private GridView mGridView;
    private UploadAdapter mAdapter;

    private List<UploadType> mSelectedUploadTypeList;

    private EasyPopupWindow mEasyPopupWindow;

    private FileUtils mFileUtils;
    private File mFile;

    private String mType;
    private boolean mIsSingle;

    public static final String UPLOAD_TYPE = "type";              //上传图片的类型
    public static final String UPLOAD_IS_SINGLE = "is_single";   //是否支持单选

    private static final int REQUEST_UPLOAD_IMAGE_CAMERA = 1;
    private static final int REQUEST_UPLOAD_IMAGE_GALLERY = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_confirm);
        Intent intent = getIntent();

        if (intent != null) {
            mType = intent.getStringExtra(UPLOAD_TYPE);
            mIsSingle = intent.getBooleanExtra(UPLOAD_IS_SINGLE, false);
        }

        initView();
        initData();
        initEvent();
    }

    private void initView() {
        mTopReturn = findView(R.id.top_return);
        mGridView = findView(R.id.grid_view);

        mSelectedUploadTypeList = new ArrayList<>();

        mFileUtils = new FileUtils();

        EventBus.getDefault().register(this);
    }

    private void initData() {
        // +
        UploadType uploadType = new UploadType();
        uploadType.setType(UPLOAD_TYPE_PLUS);
        mSelectedUploadTypeList.add(uploadType);

        /**
         * 对GridView进行测量，否则获取到的getHorizontalSpacing为0，getNumColumns为-1
         * 获取测试mode
         */
        int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        //measure一次才能获取到属性值
        mGridView.measure(width, height);

        int padding = mGridView.getPaddingLeft() + mGridView.getPaddingRight() + (mGridView.getHorizontalSpacing() * (mGridView.getNumColumns() - 1));
        mAdapter = new UploadAdapter(this, padding, mSelectedUploadTypeList);

        mGridView.setAdapter(mAdapter);
    }

    private void initEvent() {
        mTopReturn.setOnClickListener(this);

        mAdapter.setOnItemPreviewListener(new OnItemPreviewListener() {
            @Override
            public void onItemPreview(List<UploadType> selectedUploadTypeList, int position) {
                //预览图片
                Bundle bundle = new Bundle();
                bundle.putSerializable(Constant.KEY_UPLOAD_LIST, (Serializable) selectedUploadTypeList);
                bundle.putInt(Constant.kEY_UPLOAD_POSITION, position);
                startActivity(PreviewImageActivity.class, bundle, false);
            }
        });

        mAdapter.setOnItemUploadListener(new OnItemUploadListener() {
            @Override
            public void onItemUpload(String path) {
                //重新上传
                List<String> selectedImageList = new ArrayList<>();
                selectedImageList.add(path);
                uploadFile(selectedImageList);
            }
        });

        mAdapter.setOnItemPlusListener(new OnItemPlusListener() {
            @Override
            public void onItemPlus() {
                mEasyPopupWindow = PopUpUtils.showPopUpBottom(R.layout.upload_image_popupwindow, UploadConfirmActivity.this, findViewById(android.R.id.content), true, UploadConfirmActivity.this);
            }
        });
    }

    public void onEventMainThread(UploadImageEvent event) {
        int position = Integer.parseInt(event.getMsg());

        mSelectedUploadTypeList.remove(position);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtils.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> permissionList) {
        //当requestCode相同时候，permissions.size == 请求的权限数时候，认为权限请求成功
        if (requestCode == 1 && permissionList.size() == 2) {
            Intent intent = new Intent();
            // 指定开启系统相机的Action
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            // 根据文件地址创建文件
            mFile = mFileUtils.getImagesFile("IMG_" + DateUtil.formatDate(System.currentTimeMillis(), "yyyyMMdd_HHmmss") + ".jpg");

            Uri uri;

            //判断是否是AndroidN以及更高的版本
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + BuildConfig.ProviderSuffix, mFile);
            } else {
                // 把文件地址转换成Uri格式
                uri = Uri.fromFile(mFile);
            }

            // 设置系统相机拍摄照片完成后图片文件的存放地址
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, REQUEST_UPLOAD_IMAGE_CAMERA);
        } else if (requestCode == 2 && permissionList.size() == 1) {
            if (!mIsSingle) {
                startActivityForResult(UploadImageActivity.class, REQUEST_UPLOAD_IMAGE_GALLERY, null);
            } else {
                startActivityForResult(SelectImageActivity.class, REQUEST_UPLOAD_IMAGE_GALLERY, null);
            }
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> permissionList) {
        //调用了一次拒绝权限认为失败
        ToastUtils.showToast("拒绝了权限" + permissionList.get(0));
        PermissionUtils.permissionDialog(this, permissionList, null);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_UPLOAD_IMAGE_CAMERA:
                    if (mFile != null) {
                        addUploadType(mFile.getAbsolutePath());
                        mAdapter.notifyDataSetChanged();

                        //上传文件
                        List<String> selectedImageList = new ArrayList<>();
                        selectedImageList.add(mFile.getAbsolutePath());
                        uploadFile(selectedImageList);
                    }
                    break;
                case REQUEST_UPLOAD_IMAGE_GALLERY:
                    if (data != null) {
                        if (!mIsSingle) {
                            List<String> selectedImageList = (List<String>) data.getSerializableExtra(Constant.KEY_UPLOAD_LIST);

                            for (String selectedImagePath : selectedImageList) {
                                addUploadType(selectedImagePath);
                            }

                            mAdapter.notifyDataSetChanged();

                            //上传文件
                            uploadFile(selectedImageList);
                        } else {
                            String selectedImagePath = data.getStringExtra(KEY_SELECT_IMAGE_PATH);

                            List<String> selectedImageList = new ArrayList<>();

                            selectedImageList.add(selectedImagePath);

                            uploadFile(selectedImageList);
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void getChildView(int layoutId, View view) {
        Button take = (Button) view.findViewById(R.id.btn_take_photo);
        Button gallery = (Button) view.findViewById(R.id.btn_gallery);
        Button cancel = (Button) view.findViewById(R.id.btn_cancel);

        take.setOnClickListener(this);
        gallery.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.top_return) {
            finishActivity();
        } else if (id == R.id.btn_take_photo) {
            PermissionUtils.requestPermissions(this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 1);
        } else if (id == R.id.btn_gallery) {
            PermissionUtils.requestPermissions(this, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE }, 2);
        } else if (id == R.id.btn_cancel) {

        }

        if (mEasyPopupWindow != null && mEasyPopupWindow.isShowing()) {
            mEasyPopupWindow.dismiss();
        }
    }

    private void addUploadType(String selectedImagePath) {
        UploadType uploadType = new UploadType();
        uploadType.setPath(selectedImagePath);
        uploadType.setType(UPLOAD_TYPE_IMAGE);
        uploadType.setProgress(0);
        uploadType.setSuccess(true);   //默认都是能上传成功
        uploadType.setFinish(false);

        mSelectedUploadTypeList.add(mSelectedUploadTypeList.size() - 1, uploadType);
    }

    private void uploadFile(final List<String> selectedImageList) {
        if (selectedImageList == null || (selectedImageList != null && selectedImageList.size() == 0)) {
            return;
        }

        String uri;

        if (mType != null && "URL_UPLOADS_ITEM".equals(mType)) {
            uri =  Constant.URL_UPLOADS_ITEM;
        } else {
            uri =  Constant.URL_UPLOADS_AVATAR;
        }

        NoHttpUtils.httpUploadFileRequest(uri, selectedImageList, new NoHttpUtils.OnFileUploadListener() {
            @Override
            public void onStart(int position) {

            }

            @Override
            public void onCancel(int position) {

            }

            @Override
            public void onProgress(int position, int progress) {
                UploadType uploadType = mSelectedUploadTypeList.get(position);
                uploadType.setProgress(progress);

                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFinish(int position) {
                final UploadType uploadType = mSelectedUploadTypeList.get(position);
                uploadType.setFinish(true);

                mAdapter.notifyDataSetChanged();

                //上传完成
                ThreadUtils.newThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mFile != null) {
                            // 把文件插入到系统图库
                            try {
                                String uri = MediaStore.Images.Media.insertImage(getContentResolver(), mFile.getAbsolutePath(), mFile.getName(), null);

                                //插入到系统相册后，切换路径
                                uploadType.setPath(mFileUtils.getRealPathFromURI(UploadConfirmActivity.this, Uri.parse(uri)));
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            }

                            // 通知图库更新
                            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + mFile.getAbsolutePath())));

                            //删除文件
                            mFile.delete();
                        }
                    }
                });
            }

            @Override
            public void onError(int position, Exception exception) {
                UploadType uploadType = mSelectedUploadTypeList.get(position);
                uploadType.setSuccess(false);

                mAdapter.notifyDataSetChanged();
            }
        }, new NoHttpUtils.OnFileUploadResultListener() {
            @Override
            public void onSucceed(int what, FileUploadBean fileUploadBean) {
                //所有图片上传成功
                if (mIsSingle) {
                    fileUploadBean.setPath(selectedImageList.get(0));
                    finishActivity();
                }

                EventBus.getDefault().post(new UploadSuccessEvent(fileUploadBean));
            }

            @Override
            public void onFailed(int what, FileUploadBean fileUploadBean) {
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }
}
